package com.example.web;

import com.example.databean.LoginParam;
import com.example.databean.UserParam;
import com.example.service.UserInfoService;
import com.example.vo.UserAccess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserInfoService userInfoService;

    // 跳转到登录模块相应界面
    @GetMapping("/")
    public String toLogin(){
        log.info("登录界面!");
        return "login";
    }
    @GetMapping("/toRegister")
    public String toRegister() {
        log.info("注册界面!");
        return "register";
    }

    /**
     * 验证用户名或手机号码是否已经存在
     * @param checkUser
     * @param resp
     * @throws Exception
     */
    @GetMapping("/checkUser")
    public void checkUserId(String checkUser, HttpServletResponse resp) throws Exception {
        log.info("Check UserId Or Phone: " + checkUser);
        UserAccess userAccess = userInfoService.getUserInfoByUserIdOrPhone(checkUser);
        if(null != userAccess) {

            Map<String, String> map = new HashMap<>();
            map.put("message","已存在，请重新输入!");
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().println(map.toString());
            resp.getWriter().close();
        }

    }

    /**
     * 注册用户
     * @param userParam
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserParam userParam, BindingResult result, ModelMap model) {
        log.info("Register Param: " + userParam.toString());
        model.addAttribute("userParam", userParam);
        if("login".equals(this.redirectLogin(result, model))){
            return "register";
        }

        UserAccess user = userInfoService.getUserInfoByUserIdOrPhone(userParam.getUserId());
        if (user != null) {
            model.addAttribute("errorMsg", "用户名已存在，请重新输入!");
            return "register";
        }

        user = userInfoService.getUserInfoByUserIdOrPhone(userParam.getPhone());
        if (user != null) {
            model.addAttribute("errorMsg", "手机号码已存在，请重新输入!");
            return "register";
        }

        boolean res = userInfoService.register(userParam);
        if(res){
            model.addAttribute("errorMsg", "恭喜您成功注册为会员!");
            return "login";
        }else{
            model.addAttribute("errorMsg", "注册失败!");
            model.addAttribute("userParam", userParam);
            return "register";
        }

    }

    /**
     * 登录
     * @param loginParam
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PostMapping("/login")
    public String login(@Valid LoginParam loginParam, BindingResult result, ModelMap model, HttpServletRequest request){
        log.info("Login Controller!!!");
        if("login".equals(this.redirectLogin(result, model))){
            return "login";
        }

        log.info("Login Param: " + loginParam);
        UserAccess user = userInfoService.login(loginParam);
        if(null == user){
            model.addAttribute("errorMsg", "用户名不存在!");
            return "login";
        }else if(!user.getLoginPassword().equals(loginParam.getLoginPassword())){
            model.addAttribute("errorMsg", "密码错误!");
            return "login";
        }

        return "main";
    }


    // 处理相应请求
    private String redirectLogin(BindingResult result, ModelMap model) {
        String errorMsg = "";
        if(result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for(ObjectError error : list) {
                errorMsg += error.getDefaultMessage() + ".<br>";
            }
            model.addAttribute("errorMsg", errorMsg);
            log.info("Error Msg: {}", errorMsg);
            return "login";
        }else{
            return "";
        }
    }

}
